package com.efounder.message.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.efounder.message.model.MessageModel;
import com.efounder.message.struct.IMStruct002;

import net.sf.json.JSON;
import net.sf.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class MessageModelDBManager {
    private SQLiteDatabase db;
    private MessageDBHelper helper;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());

    public MessageModelDBManager(SQLiteOpenHelper helper) {
        this.db = helper.getWritableDatabase();
    }

    public long insertMessageModel(MessageModel model) {
        ContentValues values = this.getMessageModelContentValues(model);
        return this.db.insertWithOnConflict("ReadCount", (String) null, values, 5);
    }

    public void insertMessageModel(List<MessageModel> models) {
        this.db.beginTransaction();
        Iterator localIterator = models.iterator();

        while (localIterator.hasNext()) {
            MessageModel model = (MessageModel) localIterator.next();
            this.insertMessageModel(model);
        }

        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    public void updateMessageModel(List<MessageModel> models) {
        SQLiteDatabase db = this.helper.getWritableDatabase();
        this.db.beginTransaction();
        Iterator localIterator = models.iterator();

        while (localIterator.hasNext()) {
            MessageModel model = (MessageModel) localIterator.next();
            this.updateMessageModel(model);
        }

        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    public int updateMessageModel(MessageModel model) {
        ContentValues values = this.getMessageModelContentValues(model);
        String whereClause = "id=?";
        String[] whereArgs = new String[]{String.valueOf(model.getUserID())};
        return this.db.update("ReadCount", values, whereClause, whereArgs);
    }

    public void delete(MessageModel model) {
        String sql = "update ReadCount set enable = 0 where id = ? ;";
        Object[] objects = new Object[]{String.valueOf(model.getUserID())};
        this.db.execSQL(sql, objects);
    }

    public void delete(List<MessageModel> models) {
        this.db.beginTransaction();
        Iterator localIterator = models.iterator();

        while (localIterator.hasNext()) {
            MessageModel model = (MessageModel) localIterator.next();
            this.delete(model);
        }

        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    public MessageModel query(String id) {
        String sql = "select * from ReadCount left join Message on  Message.msgID = readCount.messageID where readcount.enable =1 and ReadCount.id  =\'" + id + "\'";
        List list = this.queryMessageModel(sql);
        return list.size() == 0 ? null : (MessageModel) list.get(0);
    }

    public List<MessageModel> queryMessageModel(String sql) {
        return this.query(sql, (String[]) null);
    }

    public List<MessageModel> query(String sql, String[] selectionArgs) {
        ArrayList list = new ArrayList();
        Cursor cursor = this.db.rawQuery(sql, selectionArgs);

        while (cursor.moveToNext()) {
            MessageModel model = new MessageModel();
            if (!"".equals(cursor.getString(cursor.getColumnIndex("msgID"))) && cursor.getString(cursor.getColumnIndex("msgID")) != null) {
                IMStruct002 struct002 = new IMStruct002();
                struct002.setMsgId(cursor.getInt(cursor.getColumnIndex("messageId")));
                struct002.setMessageID(cursor.getString(cursor.getColumnIndex("msgID")));
                struct002.setFromUserId(cursor.getInt(cursor.getColumnIndex("fromUserId")));
                struct002.setToUserId(cursor.getInt(cursor.getColumnIndex("toUserId")));
                struct002.setToUserType((byte) cursor.getInt(cursor.getColumnIndex("toUserType")));
                struct002.setMessageChildType((short) ((byte) cursor.getInt(cursor.getColumnIndex("messageChildType"))));
                struct002.setBody(cursor.getBlob(cursor.getColumnIndex("body")));
                struct002.setState(cursor.getInt(cursor.getColumnIndex("state")));
                struct002.setReadState(cursor.getInt(cursor.getColumnIndex("readState")));
                struct002.setVersion(cursor.getShort(cursor.getColumnIndex("version")));
                struct002.setpMsgId(cursor.getString(cursor.getColumnIndex("pMsgId")));
                struct002.setpUserId(cursor.getInt(cursor.getColumnIndex("pUserId")));
                struct002.setRecall(cursor.getInt(cursor.getColumnIndex("isRecall")) == 1);

                try {
                    Date var91 = this.dateFormat.parse(cursor.getString(cursor.getColumnIndex("time")));
                    struct002.setTime(var91.getTime());
                    Date localTime;
                    if (cursor.getString(cursor.getColumnIndex("serverTime")) != null) {
                        localTime = this.dateFormat.parse(cursor.getString(cursor.getColumnIndex("serverTime")));
                        struct002.setServerTime(localTime.getTime());
                    } else if (cursor.getString(cursor.getColumnIndex("time")).length() == 10) {
                        var91 = this.dateFormat.parse(cursor.getString(cursor.getColumnIndex("time")) + "000");
                        struct002.setServerTime(var91.getTime());
                    } else {
                        struct002.setServerTime(var91.getTime());
                    }

                    if (cursor.getString(cursor.getColumnIndex("localTime")) != null) {
                        localTime = this.dateFormat.parse(cursor.getString(cursor.getColumnIndex("localTime")));
                        struct002.setLocalTime(localTime.getTime());
                    } else if (cursor.getString(cursor.getColumnIndex("time")).length() == 10) {
                        var91 = this.dateFormat.parse(cursor.getString(cursor.getColumnIndex("time")) + "000");
                        struct002.setLocalTime(var91.getTime());
                    } else {
                        struct002.setLocalTime(var91.getTime());
                    }
                } catch (ParseException var9) {
                    var9.printStackTrace();
                }
                String extra = cursor.getString(cursor.getColumnIndex("extra"));
//				if (extra != null && !"".equals(extra)) {
//					try {
//						Map<String, Object> extraMap = new Gson().fromJson(extra, new TypeToken<HashMap<String, Object>>() {
//						}.getType());
//						struct002.setExtMap(extraMap);
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//				}
                if (extra != null && !"".equals(extra) && !"{}".equals(extra)) {
                    try {
                        Map<String, Object> extraMap1 = JSONObject.fromObject(extra);
                        HashMap<String, Object> extraMap = new HashMap<>();
                        for (String key : extraMap1.keySet()) {
                            if (extraMap1.get(key) instanceof JSON) {
                                extraMap.put(key, extraMap1.get(key).toString());
                            } else {
                                extraMap.put(key, extraMap1.get(key));
                            }
                        }
                        struct002.setExtMap(extraMap);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                model.setLastMessage(struct002);
            } else {
                model.setLastMessage((IMStruct002) null);
            }

            model.setUserID(cursor.getString(cursor.getColumnIndex("id")));
            model.setUnReadCount(cursor.getInt(cursor.getColumnIndex("unReadCount")));
            model.setAtMessageID(cursor.getString(cursor.getColumnIndex("atMessageID")));

            list.add(model);
        }

        cursor.close();
        return list;
    }

    private ContentValues getMessageModelContentValues(MessageModel model) {
        ContentValues values = new ContentValues();
        values.put("id", model.getUserID());
        if (model.getLastMessage() != null) {
            values.put("messageID", model.getLastMessage().getMessageID());
        } else {
            values.put("messageID", "");
        }
        values.put("atMessageID", model.getAtMessageID());
        values.put("unReadCount", Integer.valueOf(model.getUnReadCount()));
        values.put("enable", Integer.valueOf(1));
        return values;
    }
}
